public class ThreadOrderExecution {

    // 定义三个线程类，分别对应 t1, t2, t3
    private static final Object lock = new Object();

    private static class Thread1 extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("t1");
                lock.notify(); // 通知 t2 执行
                try {
                    lock.wait(); // 等待 t2 执行完毕
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static class Thread2 extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                try {
                    lock.wait(); // 等待 t1 执行完毕
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t2");
                lock.notify(); // 通知 t3 执行
            }
        }
    }

    private static class Thread3 extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                try {
                    lock.wait(); // 等待 t2 执行完毕
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t3");
                lock.notify(); // 通知 t1 执行（其实已经是最后一个线程，不再需要通知）
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建线程 t1, t2, t3
        Thread t1 = new Thread1();
        Thread t2 = new Thread2();
        Thread t3 = new Thread3();

        // 启动线程
        t1.start();
        t2.start();

        t3.start();
    }
}
